package com.cz.fra.android.logic;

import java.util.ArrayList;

import com.cz.fra.android.data.FishReport.UserTable;
import com.cz.fra.android.entity.User;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;

public class UserLogic {

	private static UserLogic instance;
	
	private ContentResolver cr;

	private Context mContext;
	
	private UserLogic(Context context) {
		mContext = context;
		cr = mContext.getContentResolver();
	}
	
	public static UserLogic getInstance(Context context) {
		if (instance == null) {
			instance = new UserLogic(context);
		}
		return instance;
	}
	
	public synchronized void insertUsers(ArrayList<User> list) {
		if (cr == null) {
			cr = mContext.getContentResolver();
		}

		int length = list.size();
		Log.e("insertUserList start", System.currentTimeMillis() + "");
		ContentValues[] values = new ContentValues[length];
		for (int i = 0; i < length; i++) {
			User r = list.get(i);
			values[i] = r.instanceToCV();
		}
		cr.bulkInsert(UserTable.CONTENT_URI, values);
		synchronized (list) {
			list.clear();
		}
		Log.e("insertUsers end", System.currentTimeMillis() + "");
	}
	
	
	public User getUser(int uid){
		if (cr == null) {
			cr = mContext.getContentResolver();
		}
		Cursor cursor = cr.query(UserTable.CONTENT_URI, null, UserTable.UID+ "=" + "'" + uid+ "'", null, null);
		User user = new User();
		if (cursor.moveToFirst()) {
			user.setUserid(cursor.getInt(cursor.getColumnIndex(UserTable.UID)));
			user.setUsername(cursor.getString(cursor.getColumnIndex(UserTable.USER_NAME)));
			user.setProfileImage(cursor.getString(cursor.getColumnIndex(UserTable.PROFILE_IMG)));
		}
		cursor.close();
		return user;
	}

	public User getUser() {
		if (cr == null) {
			cr = mContext.getContentResolver();
		}
		Cursor cursor = cr.query(UserTable.CONTENT_URI, null, null, null, null);
		User user = new User();
		if (cursor.moveToFirst()) {
			user.setUserid(cursor.getInt(cursor.getColumnIndex(UserTable.UID)));
			user.setUsername(cursor.getString(cursor.getColumnIndex(UserTable.USER_NAME)));
			user.setProfileImage(cursor.getString(cursor.getColumnIndex(UserTable.PROFILE_IMG)));
		}
		cursor.close();
		return user;
	}
}
